﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Configuration;
using ZX.DBModule;
using ZX.Common;
using ZX.BLL;

namespace UploadWcfService
{
    // 注意: 如果更改此处的类名 "UpLoadService"，也必须更新 Web.config 中对 "UpLoadService" 的引用。
    public class UpLoadService : IUpLoadService
    {
        public void UploadFile(FileUploadMessage request)
        {
           

            string json = request.SavePath;
            iSun.Entity.ProductImage entity = ZX.Common.Globals.JSonToObject<iSun.Entity.ProductImage>(json);
            entity.AddTime = System.DateTime.Now;
            entity.AddUser = Guid.Empty;
            entity.DateLastModified = System.DateTime.Now;
            string savaPath = entity.FilePath;
            entity.FilePath = (entity.StepN == 0 ? "\\Upload\\Photo\\" : "\\Upload\\Photo1\\") + entity.FilePath + entity.fileName;
            string uploadFolder =entity.StepN==0? ConfigurationManager.AppSettings["filePath"]: ConfigurationManager.AppSettings["filePath1"];
            
            iSun.Entity.ProductPhotoEnitty _entity = new iSun.Entity.ProductPhotoEnitty();
            ZX.BLL.Extend.BaseBussnies _bll = new ZX.BLL.Extend.BaseBussnies(_entity);

            IList<iSun.Entity.ProductPhotoEnitty> __list = _bll.GetEntitys<iSun.Entity.ProductPhotoEnitty>("SN='"+entity.SN+"'");
            if (__list == null)
            {
                //iSun.Entity.ProductPhotoEnitty __entity = new iSun.Entity.ProductPhotoEnitty();
                _entity.ID = new Guid();
                _entity.SN = entity.SN;
                _entity.ProductName = entity.SN;
                _entity.AddTime = System.DateTime.Now;
                SaveProductData(_entity);
                entity.ProductID = _entity.ID; 
            }
            else
            {
                entity.ProductID = __list[0].ID;
            }
            string dateString = DateTime.Now.ToShortDateString() + @"\";
            string fileName = request.FileName;
            Stream sourceStream = request.FileData;
            FileStream targetStream = null;
           
            if (!sourceStream.CanRead)
            {
                throw new Exception("数据流不可读!");
            }
            if (savaPath == null) savaPath = @"Photo\";
            if (!savaPath.EndsWith("\\")) savaPath += "\\";

            uploadFolder = uploadFolder + savaPath;
            if (!Directory.Exists(uploadFolder))
            {
                Directory.CreateDirectory(uploadFolder);
            }

            string filePath = (uploadFolder+fileName);
            using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                //read from the input stream in 4K chunks
                //and save to output stream
                const int bufferLen = 4096;
                byte[] buffer = new byte[bufferLen];
                int count = 0;
                while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                {
                    targetStream.Write(buffer, 0, count);
                }
                targetStream.Close();
                sourceStream.Close();
                SaveFileData(entity);
            }
        }
        public FileUploadMessage GetProduct(DownloadRequest request)
        {
            FileUploadMessage data = new FileUploadMessage();

            System.IO.Stream sourceStream = new FileStream(ConfigurationManager.AppSettings["filePath"] + request.FileName, FileMode.Open);
     
            data.FileData = sourceStream;
            //sourceStream.Close();
            //sourceStream.Close();
            return data;
            //return file;
        }

        public void UploadProduct(string request)
        {
            IList<iSun.Entity.ProductPhotoEnitty> list = ZX.Common.Globals.JSonToObject<IList<iSun.Entity.ProductPhotoEnitty>>(request);
            iSun.Entity.ProductPhotoEnitty entity = new iSun.Entity.ProductPhotoEnitty();
            ZX.BLL.Extend.BaseBussnies _bll = new ZX.BLL.Extend.BaseBussnies(entity);

            IList<iSun.Entity.ProductPhotoEnitty> _list = _bll.GetEntitys<iSun.Entity.ProductPhotoEnitty>();
            foreach (iSun.Entity.ProductPhotoEnitty _entity in list)
            {
                if (_list==null || _list.Where(p => p.SN == _entity.SN).Count() == 0)
                {
                    SaveProductData(_entity);
                }
            }
        }

        public IList<string> GetFiles()
        {
            IList<string> list = new List<string>();
            string uploadFolder = ConfigurationManager.AppSettings["filePath"];
            DirectoryInfo dir = new DirectoryInfo(uploadFolder);
            FileInfo[] allFile = dir.GetFiles();
            uFile(uploadFolder, uploadFolder, list);
            return list;
        }


        public IList<string> GetSNFiles(string SN)
        {
            IList<string> list = new List<string>();
            string uploadFolder = ConfigurationManager.AppSettings["filePath"]+SN;
            DirectoryInfo dir = new DirectoryInfo(uploadFolder);
            FileInfo[] allFile = dir.GetFiles();
            uFile(uploadFolder, uploadFolder, list);
            return list;
        }


        void uFile(string path,string mainPath, IList<string> list)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] allFile = dir.GetFiles();
            foreach (FileInfo fi in allFile)
            {
                list.Add(fi.FullName.Replace(mainPath, ""));
            }
            foreach (DirectoryInfo _dir in dir.GetDirectories())
            {
                uFile(_dir.FullName,mainPath,list);
            }
        }
        public void SaveFileData(iSun.Entity.ProductImage entity)
        {           
            //ZX.DBModule.DataTableBaseEntity dtEntity = new DataTableBaseEntity();
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(entity);
            bll.Insert();
        }

        //public void SaveFileData(iSun.Entity.ProductImage entity)
        //{
        //    //ZX.DBModule.DataTableBaseEntity dtEntity = new DataTableBaseEntity();
        //    ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(entity);
        //    bll.Insert();
        //}
        
        public void SaveProductData(iSun.Entity.ProductPhotoEnitty entity)
        {
            //ZX.DBModule.DataTableBaseEntity dtEntity = new DataTableBaseEntity();
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(entity);
            bll.Insert();
        }

        public bool IsExistsProduct(string SN)
        {
            iSun.Entity.ProductPhotoEnitty entity = new iSun.Entity.ProductPhotoEnitty();
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(entity);
            entity = bll.GetEntityByCondition<iSun.Entity.ProductPhotoEnitty>("SN='" + SN + "'");
            return entity != null;
        }

        public void DeleteProuct(string SN)
        {
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            bll.RunSqlCommand(string.Format("delete from gs_ProductImage where SN='{0}';delete from gs_Product where SN='{0}';", SN));

            try
            {
                string sourcePath = ConfigurationManager.AppSettings["filePath"];
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(sourcePath + SN);
                dir.Delete(true);
                string tagetPath = ConfigurationManager.AppSettings["filePath1"];
                System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(sourcePath + SN);
                dir1.Delete(true);
            }
            catch (Exception e1)
            {
            }
        }

        public void DeleteProuctImages(string images)
        {
            string[] imagePath = images.Split(',');
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            foreach (string _image in imagePath)
            {
                string webPath = ConfigurationManager.AppSettings["filePath"].Replace("\\upload\\Photo","");
                webPath = webPath + _image;
                if (System.IO.File.Exists(webPath))
                {
                    System.IO.File.Delete(webPath);
                }
                
                bll.RunSqlCommand(string.Format("delete from gs_ProductImage where FilePath='{0}';", _image));
            }
        }

        public void SetFlag(string SN, string Flag)
        {
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies();
            bll.RunSqlCommand(string.Format("update gs_Product set {0}='1' from gs_ProductImage where SN='{1}';",Flag,SN));
        }
    }
}
